package com.king.pattem.singleton.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *	单例模式应用-单例类应用-配置文件管理
 * @author taomk
 */
public class ConfigManager {
	/**
     * 属性文件全名
     */
    private static final String PFILE = "C:\\xxx.properties";
    /**
     * 对应于属性文件的文件对象变量
     */
    private File m_file = null;
    /**
     * 属性文件的最后修改日期
     */
    private long m_lastModifiedTime = 0;
    /**
     * 属性文件所对应的属性对象变量
     */
    private Properties m_props = null;
    /**
     * 本类可能存在的唯一的一个实例
     */
    private static ConfigManager m_instance = new ConfigManager();
    /**
     * 私有构造子,用以保证外界无法直接实例化
     */
    private ConfigManager() {
        m_file = new File(PFILE);
        m_lastModifiedTime = m_file.lastModified();
        if (m_lastModifiedTime == 0) {
            System.err.println(PFILE + " file does not exist!");
        }
        m_props = new Properties();
        try {
            m_props.load(new FileInputStream(PFILE));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 静态工厂方法
     *
     * @return ConfigManager
     */
    public final synchronized static ConfigManager getInstance() {
        return m_instance;
    }
    /**
     * 获取属性配置项的值
     *
     * @param name
     * @param defaultVal
     * @return Object
     */
    public final Object getConfigItem(String name, Object defaultVal) {
        long newTime = m_file.lastModified();
        if (newTime == 0) {
            //属性文件不存在
            if (m_lastModifiedTime == 0) {
                System.err.println(PFILE + " file does not exist!");
            } else {
                System.err.println(PFILE + " file was deleted!");
            }
            return defaultVal;
        } else if (newTime > m_lastModifiedTime) {
            m_props.clear();
            try {
                m_props.load(new FileInputStream(PFILE));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        m_lastModifiedTime = newTime;
        Object val = m_props.getProperty(name);
        if (val == null) {
            return defaultVal;
        } else {
            return val;
        }
    }
}
